package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.MD5;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpCoupon;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.McCreditsJournal;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.RsSms;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.TsClassifiedAccount;
import cn.jekun.component.core.service.AccountPayService;
import cn.jekun.component.core.service.ProfitService;
import cn.jekun.component.core.service.SMSService;
import cn.jekun.component.core.service.gen.ErpCouponService;
import cn.jekun.component.core.service.gen.ErpShopService;
import cn.jekun.component.core.service.gen.McCreditsJournalService;
import cn.jekun.component.core.service.gen.McMemberService;
import cn.jekun.component.core.service.gen.RsSmsService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.core.service.gen.TsClassifiedAccountService;

@Service(RegService.BEAN_NAME)
public class RegService extends ShopBaseService {
	public static final String BEAN_NAME = "cn.jekun.shop.common.RegService";
	public static final String NAMESPACE = "SHOP_REGISTER";
	public static final int DDP_SCORE = 10;
	
	@Resource(name = AccountPayService.BEAN_NAME)
	private AccountPayService accountPayService;
	
	@Resource(name=ErpCouponService.BEAN_NAME)
	private ErpCouponService erpCouponService;
	
	@Resource(name = TsClassifiedAccountService.BEAN_NAME)
	TsClassifiedAccountService tsClassifiedAccountService;
	
	@Override
	public String getNamespace() {
		return NAMESPACE;
	}

	@Resource(name = RsUserService.BEAN_NAME)
	RsUserService rsUserService;
	@Resource(name = McMemberService.BEAN_NAME)
	McMemberService mcMemberService;

	@Resource(name = RsSmsService.BEAN_NAME)
	RsSmsService rsSmsService;

	 @Resource(name = ErpShopService.BEAN_NAME)
	 ErpShopService erpShopService;
	 
	 /*@Resource(name=DdpService.BEAN_NAME)
	 DdpService ddpService;*/
	 
	 @Resource(name = McCreditsJournalService.BEAN_NAME)
	 McCreditsJournalService mcCreditsJournalService;
	 
	@Resource(name=ProfitService.BEAN_NAME)
	ProfitService profitService;
		
	 
	 /**
	  * 注册
	  * @param mobile 手机号
	  * @param password 密码
	  * @param validateCode 手机验证码
	  * @param come 来源
	  * @param memberTypeId 会员加入方式代码
	  * @param terminalId 终端代码
	  * @return
	  */
	@Transactional
	@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
	public JSONObject register(
			@Mobile(message="手机号非法")
			String mobile, 
			@MD5(message="密码未加密")
			String password,
			@Security
			String validateCode, 
			@Security
			String come,
//			@Security
//			String email,
			@Security
			String terminalId,
			@Security
			String memberTypeId ) {
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		JSONObject jsonObject = new JSONObject();
		String shopId = "";
		String userId = "";
		RsUser user1 = new RsUser();
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机不能为空");
		}
//		if(StringUtils.isNotBlank(terminalId)){
//			user1.setTerminalId(terminalId); 
//		}
		if (StringUtils.isBlank(password)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"密码不能为空");
		}
		if (StringUtils.isBlank(validateCode)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"短信验证码不为空");
		}
		password = this.versionCompatible(password);
		McMember member = new McMember();
		//--------------验证来源是否是商家还是会员-----------------
		if(StringUtils.isNotBlank(come)){
			Map shopMap = new HashMap();
			shopMap.put(ErpShop.COL_SHOP_ID, come);
			SqlUtis.prepareSql(shopMap, "", SqlUtis.getSQL(shopMap, "a."
					+ ErpShop.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));
			boolean tempFlag = this.erpShopService.exists(shopMap);
			Map userMap = new HashMap();
			userMap.put(RsUser.COL_USER_ID, come);
			SqlUtis.prepareSql(userMap, "", SqlUtis.getSQL(userMap, "a."
					+ RsUser.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ));
			boolean userFlag = this.rsUserService.exists(userMap);
			if(tempFlag){
				shopId = come;
				user1.setShopId(shopId);//开户商家
				member.setShopId(shopId);
			} else if(userFlag){
				userId = come;
				//通过userId找到其对应的开户商家shopId并将其对应的商家填充到被发展的会员信息中去
				RsUser tempUser = this.rsUserService.one(userId);
				user1.setShopId(StringUtils.isBlank(tempUser.getShopId())?"":tempUser.getShopId());
				user1.setInviteUserId(userId);//邀请人
			}else {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"找不到邀请人或者商家信息");
			}
		}
		
		//---------------验证来源是否是会员---------------------
		// 短信验证码验证（查找最新的短信信息验证码）
		String tempCode = null;// 手机验证码
		Map tempSmsMap = new HashMap();
		tempSmsMap.put(RsSms.COL_MOBILE, mobile);
		tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.REG_CODE);
		SqlUtis.prepareSql(tempSmsMap, "and round(to_number(sysdate - a.create_time) * 1440) < 30", 
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
				.orderBy(" a.create_time desc nulls last"));
		Page smsPage = new Page();
		smsPage.setPageSize(1);
		List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
		if (smsList != null && smsList.size() >= 1) {
			RsSms rsSms = smsList.get(0);
			tempCode = rsSms.getMemo();
		}
		if (!validateCode.equals(tempCode)) {
			throw new BusinessException("-3210",
					"验证码错误");
		}
		//-----------------------------------------------------------------------------
		formMap.put(RsUser.COL_USER_NAME, mobile);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "b."
				+ RsUser.COL_USER_NAME, Types.VARCHAR, SqlUtis.EQ));
		Map tempUserMap1 = new HashMap();
		tempUserMap1.put(RsUser.COL_USER_NAME, mobile);
		SqlUtis.prepareSql(tempUserMap1, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_USER_NAME, Types.VARCHAR, SqlUtis.EQ));
		RsUser user = this.rsUserService.one(tempUserMap1);
		String returnUserId = null;
		if (user != null) {
			returnUserId = user.getUserId();
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"该用户已存在");
		} else {
			// 3:加用户
			Map userMap = new HashMap();
			Map tempUserMap = new HashMap();
			user1.setUserName(mobile);// 用户名
			user1.setMobile(mobile);// 手机号
			user1.setPassword(password);
			user1.setRealName(mobile);
			user1.setPhoneNumber(mobile);
//			user1.setEmail(email);
			tempUserMap.put("rsUser", user1);
			returnUserId = this.rsUserService.insert(tempUserMap).toString();
			
			//开通个人账户
			JSONObject json = accountPayService.create(returnUserId, Constants.TS_ACCOUNT_OWNER_TYPE.USER, "password", Constants.TS_ACCOUNT_SIGN_TYPE.SIGN_TYPE_00, "0","用户注册开户",Constants.TS_ACCOUNT_STATUS.STATUS_05);
			String accountId = json.getString("accountId");
			TsClassifiedAccount tsClassifiedDay=new TsClassifiedAccount();
			tsClassifiedDay.setAccountId(accountId);
			tsClassifiedDay.setAmount(0d);
			tsClassifiedDay.setChannelId("00");//默认终端
			tsClassifiedDay.setIsDeposit(Constants.TS_ACCOUNT_ISDEPOSIT.DEPOSIT_00);
			tsClassifiedDay.setStatusId(Constants.TS_ACCOUNT_STATUS.STATUS_00);
			tsClassifiedDay.setTypeId(Constants.TS_CLASSIFIED_ACCOUNT_TYPE.CLASSIFIED_00);
			tsClassifiedDay.setCreateName("system");
			tsClassifiedAccountService.insert(tsClassifiedDay);
			/*
			//送红包
			ErpCoupon erpCoupon = new ErpCoupon();
			erpCoupon.setAmount(5d);
			erpCoupon.setAvailable("1");
			erpCoupon.setCreateName("system");
			erpCoupon.setMemo("注册送红包");
			erpCoupon.setName("注册送红包");
			erpCoupon.setType("01");
			erpCoupon.setUserId(returnUserId);
			this.erpCouponService.insert(erpCoupon );
			*/
		}
		String memberId = null;
		if (returnUserId != null) {
			if (StringUtils.isNotBlank(shopId)
					&& !Constants.COM_SHOP_ID.equals(shopId)) {
				Map tempMemberMap = new HashMap();
				member.setUserId(returnUserId);
				member.setLevelId(Constants.MC_MEMBER_LEVEL.PRIMARY);// 初级
				member.setCredits(0.0);
				member.setMemberTypeId(memberTypeId);
				tempMemberMap.put("mcMember", member);
				memberId = this.mcMemberService.insert(tempMemberMap)
						.toString();
			}
			// 赠送几分
			if (StringUtils.isNotBlank(userId)) {// 老会员
				double credit = profitService.getInviteCredit();// 老会员邀请积分
				this.sendCreditsByFanke(userId, credit,returnUserId);
			}
			double credit = profitService.getRegistCredit();// 新用户注册积分
			this.sendCreditsByFanke(returnUserId, credit,"");// 新用户
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			return executeRerutn(jsonObject);
		}
		else{
			return executeRerutnFail(jsonObject);
		}
	}
	/**
	 * 验证手机号是否注册过
	 * 
	 * @param mobile
	 *            手机号
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject validateMobile(
			@Mobile
			String mobile) {
		Map formMap = new HashMap();
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机不能为空");
		}
		formMap.put(RsUser.COL_MOBILE, mobile);
		// formMap.put(RsUser.COL_USER_TYPE, "4");
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
		boolean flag = rsUserService.exists(formMap);
		if (flag) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"此号码已存在");
		}
		return executeRerutn(jsonObject);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject sendValidateCodeByReg(
			@Mobile(message="手机号非法")
			String mobile) {
		JSONObject jsonObject = new JSONObject();
		String smsTypeId = Constants.RS_SMS_TYPE.REG_CODE;
		if (StringUtils.isEmpty(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"请输入手机号码");
		}
		SMSService.checkTime(mobile);//检查发送间隔
		//一天最多5条
		if(!this.smsService.checkOverTimes(mobile, 	smsTypeId, "24", 5)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"一天最多5条,请稍后再操作");
		}
		try {
			// 生成随机类
			Random random = new Random();
			// 取随机产生的认证码(4位数字)
			String sRand = "";
			for (int i = 0; i < 6; i++) {
				String rand = String.valueOf(random.nextInt(10));
				sRand += rand;
			}
			String content = "欢迎注册云便利商店，您的验证码"+sRand+"，请在注册页面填写。" ;
//			// 将认证码存入数据库
//			Map insertMap = new HashMap();
//			RsSms rsSms = new RsSms();
//			rsSms.setContent(content);
//			rsSms.setMemo(sRand);
//			rsSms.setMobile(mobile);
//			rsSms.setSmsTypeId(smsTypeId);// 注册验证码
//			insertMap.put("rsSms", rsSms);
//			rsSmsService.insert(insertMap);
			// 发送短信
			String error = this.smsService.sendSMS(mobile, content, smsTypeId, sRand);
			if (error != null) {
				jsonObject.put(ErrorMsg.KEY_MESSAGE, error);
				return this.executeRerutnFail(jsonObject);
			}
			return this.executeRerutn(jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			return this.executeRerutnFail(jsonObject);
		}
	}
	
	/**
	 * 赠送积分
	 * @param userId 发展人
	 * @param credit 积分数
	 * @param returnUserId 发展的新用户
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void sendCreditsByFanke(
			@Security
			String userId,double credit,String returnUserId){
		if (credit<=0) {
			return;
		}
		Map map = new HashMap();
		map.put(McMember.COL_USER_ID, userId);
		map.put(McMember.COL_SHOP_ID, Constants.COM_SHOP_ID);
		SqlUtis.prepareSql(map, "", 
				SqlUtis.getSQL(map, "a."+ McMember.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(map, "a."+ McMember.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));
		McMember tempMember = this.mcMemberService.one(map);
		McMember mcMember = new McMember();
		String memberId = null;
		if(tempMember != null){
			double tempCredit = tempMember.getCredits()+credit;
			mcMember.setCredits(tempCredit); 
			memberId = tempMember.getMemberId();
		}else{
			McMember testMember = new McMember();
			testMember.setUserId(userId);
			testMember.setShopId(Constants.COM_SHOP_ID);
			testMember.setCredits(0.0);
			testMember.setMemberTypeId("3");
			testMember.setLevelId(Constants.MC_MEMBER_LEVEL.PRIMARY);
			memberId = this.mcMemberService.insert(testMember).toString();
			mcMember.setCredits(credit); 
		}
		Map tempMap = new HashMap();
		
		tempMap.put(McMember.COL_MEMBER_ID, memberId);
		SqlUtis.prepareSql(tempMap, "", 
				SqlUtis.getSQL(tempMap, "a."+ McMember.COL_MEMBER_ID, Types.VARCHAR, SqlUtis.EQ));
		tempMap.put("mcMember", mcMember);
		this.mcMemberService.update(tempMap);
		Map insertJournalMap = new HashMap();
		McCreditsJournal mcCreditsJournal = new McCreditsJournal();
		mcCreditsJournal.setCreateName(userId);
		mcCreditsJournal.setCredits(credit);
		mcCreditsJournal.setCreditsBalance(credit);
		mcCreditsJournal.setMemberId(memberId);
		mcCreditsJournal.setOperationTypeId(Constants.MC_CREDITS_OPERATION_TYPE.REG_ADD);
		mcCreditsJournal.setShopId(Constants.COM_SHOP_ID);
		mcCreditsJournal.setMemo("赠送积分");
		if(StringUtils.isNotBlank(returnUserId)){
			mcCreditsJournal.setExt(returnUserId);
		}
		insertJournalMap.put("mcCreditsJournal", mcCreditsJournal);
		mcCreditsJournalService.insert(insertJournalMap );
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject sendValidateCodeByUpdateMobile(
			@Mobile(message="手机号非法")
			String mobile,
			@Security
			String smsTypeId) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isEmpty(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"请输入手机号码");
		}
		SMSService.checkTime(mobile);//检查发送间隔
		//一天最多5条
				if(!this.smsService.checkOverTimes(mobile, 	smsTypeId, "24", 5)){
					throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
							"一天最多5条,请稍后再操作");
				}
		try {
			// 生成随机类
			Random random = new Random();
			// 取随机产生的认证码(4位数字)
			String sRand = "";
			for (int i = 0; i < 6; i++) {
				String rand = String.valueOf(random.nextInt(10));
				sRand += rand;
			}
			String content = "您正在修改绑定手机，验证码"+sRand+"，请在页面填写，如非本人操作，请忽略。" ;
//			// 将认证码存入数据库
//			Map insertMap = new HashMap();
//			RsSms rsSms = new RsSms();
//			rsSms.setContent(content);
//			rsSms.setMemo(sRand);
//			rsSms.setMobile(mobile);
//			rsSms.setSmsTypeId(smsTypeId);// 注册验证码
//			insertMap.put("rsSms", rsSms);
//			rsSmsService.insert(insertMap);
			// 发送短信
			String error = this.smsService.sendSMS(mobile, content, smsTypeId, sRand);
			if (error != null) {
				jsonObject.put(ErrorMsg.KEY_MESSAGE, error);
				return this.executeRerutnFail(jsonObject);
			}
			return this.executeRerutn(jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			return this.executeRerutnFail(jsonObject);
		}
	}
	
}
